<template>
  <div>
    <Modal :mask-closable="false" v-model="visible" width="1000" class="addModal modal-content-item-layout" :title="!id
      ? `${$t('maintenance.addMaintenanceItem')}`
      : `${$t('maintenance.editMaintenanceItem')}`
      ">
      <div class="addProject">
        <!-- 保养内容 -->
        <div class="titleItem content-item">
          <span class="content-item-title">{{
            $t("maintenance.Maintenancecontent")
          }}</span>
          <div class="checkObject pd16">
            <div class="checkObjectItem">
              <div class="checkObjectName" :class="{ required: true }">
                {{ $t("maintenance.MaintenanceLevel") }}
              </div>
              <div class="checkObjectValue">
                <Select v-model="formInline.itemLevel" filterable clearable :placeholder="`${$t('common.selectInfo')}`"
                  class="select">
                  <Option v-for="v in levels" :value="v.value" :key="v.value" :label="v.label"></Option>
                </Select>
              </div>
            </div>
            <div class="checkObjectItem" style="flex: 1">
              <div class="checkObjectName" :class="{ required: true }">
                {{ $t("maintenance.MaintenanceItem") }}
              </div>
              <div class="checkObjectValue">
                <Input class="inputWrapper" :maxlength="100" v-model="formInline.itemProject" clearable />
              </div>
            </div>
            <div class="checkObjectItem">
              <div class="checkObjectName" :class="{ required: true }">
                基准
              </div>
              <div class="checkObjectValue">
                <Input class="inputWrapper" v-model="formInline.itemBase" clearable />
              </div>
            </div>
          </div>
          <div class="checkObject pd16" style="padding-top: 0 !important">
            <div class="checkObjectItem" style="flex: 1">
              <div class="checkObjectName" :class="{ required: true }">
                保养方法
              </div>
              <div class="checkObjectValue">
                <Input class="inputWrapper" :maxlength="100" v-model="formInline.itemMethod" clearable />
              </div>
            </div>
            <div class="checkObjectItem">
              <div class="checkObjectName" :class="{ required: true }">
                标准工时（S）
              </div>
              <div class="checkObjectValue">
                <InputNumber class="inputWrapper" :min="0" :maxlength="250" v-model="formInline.unitTime" clearable />
              </div>
            </div>
            <div class="checkObjectItem">
              <div class="checkObjectName">需求人数</div>
              <div class="checkObjectValue">
                <Input class="inputWrapper" :maxlength="250" v-model="formInline.personQty" clearable />
              </div>
            </div>
          </div>
        </div>
        <!-- 保养对象 -->
        <!-- <div class="titleItem content-item">
          <span class="content-item-title">{{
            $t("maintenance.MaintenanceObj")
          }}</span>
          <div class="checkObject pd16">
            <div class="checkObjectItem">
              <div class="checkObjectName" :class="{ required: true }">
                工装编号
              </div>
              <div class="checkObjectValue">
                <Select v-model="formInline.mmoldCode" filterable clearable class="select" :remote-method="handleRemote"
                  @on-change="deviceMIdChange" :placeholder="`${$t('common.inputInfo')}${$t(
                    'equipCheck.SerialNo'
                  )}`">
                  <Option v-for="item in deviceMIdList" :value="item.moldCode" :label="item.moldCode"
                    :key="item.moldCode"></Option>
                </Select>
              </div>
            </div>
            <div class="checkObjectItem">
              <div class="checkObjectName" :class="{ required: true }">
                工装等级
              </div>
              <div class="checkObjectValue">
                <Select v-model="formInline.moldGrade" disabled @on-change="categorySelectChange" clearable
                  :placeholder="`${$t('common.selectInfo')}`" class="select">
                  <Option v-for="v in deviceList" :value="v.value" :key="v.value" :label="v.label"></Option>
                </Select>
              </div>
            </div>
            <div class="checkObjectItem">
              <div class="checkObjectName" :class="{ required: true }">
                工装名称
              </div>
              <div class="checkObjectValue">
                <Input class="inputWrapper" readonly :maxlength="250" v-model="formInline.mmoldName" />
              </div>
            </div>
          </div>
          <div class="checkObject pd16" style="padding-top: 0 !important">
            <div class="checkObjectItem">
              <div class="checkObjectName">{{ $t('保养位置') }}</div>
              <div class="checkObjectValue">
                <Select style="width: 300px;" filterable clearable class="select" v-model="formInline.bomId"
                  :placeholder="`${$t('common.selectInfo')}`" @on-change="materielNoChangeBom"
                  :remote-method="materielNoChange">
                  <Option v-for="item in materielNoList" :value="item.id"
                    :label="item.materielNo + '-' + item.materielName" :key="item.id" />
                </Select>
              </div>
            </div>
            <div class="checkObjectItem" />
            <div class="checkObjectItem" />
          </div>
        </div> -->
        <!-- 保养sop -->
        <div class="titleItem content-item">
          <span class="content-item-title">{{ $t("保养SOP") }}</span>
          <div class="checkObject pd16">
            <div class="checkObjectItem">
              <Row style="width: 100%">
                <Col span="3">
                <van-uploader accept="*" :show-upload-list="false" :after-read="afterRead">
                  <template #preview-cover="{ file }">
                    <span class="text">{{ $t("maintenance.New") }}</span>
                  </template>
                </van-uploader>
                </Col>
                <Col span="21" v-if="tarGetattachment && tarGetattachment.length">
                <div class="fujianList">
                  <div class="item demo-upload-list" v-for="(list, index) in tarGetattachment" :key="index"
                    @click="previewClicjk(list, index, tarGetattachment)">
                    <img v-if="util.fileType(list.fileName) === 'image'" :src="list.fileUrl" alt="" />
                    <video v-else-if="util.fileType(list.fileName) === 'video'" preload="auto" loop autoplay muted>
                      <source :src="util.filePathToUrl(
                        list.filePath || list.filepath
                      )
                        " type="video/mp4" />
                    </video>
                    <span v-else class="fileSty">{{ list.fileName }}</span>
                    <!-- <span class="dleIcon" >
                      <Icon class="delIcon" type="ios-close-circle" />
                    </span> -->
                    <Icon
                      type="ios-close-circle"
                      class="delIcon"
                      @click.stop="deleteAttachment(list)"
                    />
                  </div>
                </div>
                </Col>
              </Row>
              <!--              <div class="itemCol videoCol">-->
              <!--                <van-uploader-->
              <!--                     accept="*"-->
              <!--                    :show-upload-list="false"-->
              <!--                    :after-read="afterRead"-->
              <!--                >-->
              <!--                  <template #preview-cover="{ file }">-->
              <!--                    <span class="text">{{$t('maintenance.New')}}</span>-->
              <!--                  </template>-->
              <!--                </van-uploader>-->
              <!--              </div>-->
              <!--              <div class="fujianList">-->
              <!--                <div class="item">-->
              <!--                  图片-->
              <!--                </div>-->
              <!--              </div>-->
            </div>
          </div>
        </div>
        <!-- 保养时间 -->
        <!-- <div class="titleItem content-item">
          <span class="content-item-title">{{ $t('maintenance.MaintenanceTime') }}</span>
          <div class="checkObject pd16">
            <div class="checkObjectItem" style="flex: 1">
              <div class="checkObjectName" :class="{ required: true }">{{ $t('maintenance.Frequency') }}</div>
              <div class="checkObjectValue">
                <CheckboxGroup v-model="formInline.triggerCycle">
                  <Checkbox v-for="(m, n) in weeks" :key="n" :label="m.label">{{ m.name }}</Checkbox>
                </CheckboxGroup>
              </div>
            </div>
          </div>
        </div> -->

        <!-- <div class="titleItem content-item">
          <span class="content-item-title">{{ $t('maintenance.Maintenancestandards') }}</span>
          <div class="checkObject pd16">
            <div class="checkObjectItem">
              <div class="checkObjectName" :class="{ required: true }">{{ $t('maintenance.numberRequirements') }}</div>
              <div class="checkObjectValue">
                <InputNumber :max="9999999999999999999" class="inputNumberWrapper" v-model="formInline.minValue"
                  clearable />
              </div>
            </div>
            <div class="checkObjectItem">
              <div class="checkObjectName">{{ $t('maintenance.UpperLimit') }}</div>
              <div class="checkObjectValue">
                <InputNumber :max="9999999999999999999" class="inputNumberWrapper" v-model="formInline.maxValue"
                  clearable />
              </div>
            </div>
            <div class="checkObjectItem">
              <div class="checkObjectName" :class="{ required: true }">{{ $t('maintenance.workinghours') }}</div>
              <div class="checkObjectValue">
                <InputNumber class="inputNumberWrapper" :min="0" :max="9999999999999999999" v-model="formInline.itemHours"
                  clearable />
              </div>
            </div>
            <div class="checkObjectItem">
              <div class="checkObjectName" style="width: calc(17% - 3px);border-top: none;" :class="{ required: true }">
                {{ $t('maintenance.Maintenancestandards') }}</div>
              <div class="checkObjectValue" style="width: calc(83% + 3px);border-top: none;">
                <Input class="inputWrapper" v-model="formInline.unitTime" clearable />
              </div>
            </div>
            <div class="checkObjectItem" style="flex: 1;">
              <div class="checkObjectName" :class="{ required: true }">{{ $t('maintenance.Maintenancestandards') }}</div>
              <div class="checkObjectValue">
                <Input class="inputWrapper" v-model="formInline.unitTime" clearable />
              </div>
            </div>
          </div>
        </div> -->
        <!-- 使用物料 -->
        <div class="titleItem tab content-item">
          <span class="content-item-title">{{
            $t("maintenance.Usematerial")
          }}</span>
          <div class="icon" @click="handleMaterial">
            <Icon type="md-add" color="#187BDB" />{{
              $t("maintenance.Addmaterial")
            }}
          </div>
          <div class="tableContent pd16" style="width: 100%">
            <Table class="resizable-table" border @on-column-width-resize="(a, b, c, d) => {
              onColumnWidthResize(a, b, c, d, 'Addmaterialmodaltable');
            }
              " ellipsis ref="selection" :columns="materColumns" :data="materData">
              <template slot-scope="{ row, index }" slot="num">
                <div v-if="!row.isEdit">
                  <Row>
                    <Col :span="20">
                    <span>{{ row.qty }}</span>
                    </Col>
                    <Col :span="4" v-if="!row.numStatus">
                    <Icon type="ios-brush-outline" size="18" color="#180fff" @click="handleToolsEdit(row, index)" />
                    </Col>
                  </Row>
                </div>
                <div v-else>
                  <Row>
                    <Col :span="20">
                    <InputNumber :min="1" v-model="row.qty" />
                    </Col>
                    <Col :span="4">
                    <Icon type="ios-checkmark" size="35" color="#180fff" @click="handleMaterEdit(row, index)"
                      style="display: inline-block" />
                    </Col>
                  </Row>
                </div>
              </template>
              <template slot-scope="{ row }" slot="action">
                <!--            <span class="operationBtn" @click="handleToolsEdit(row,index)">{{$t('common.Edit')}}</span>-->
                <span class="operationBtn" @click="handlemDelete(row)">{{
                  $t("common.Delete")
                }}</span>
              </template>
            </Table>
          </div>
        </div>
        <!-- 使用工具 -->
        <div class="titleItem tab content-item">
          <span class="content-item-title">{{
            $t("maintenance.usetools")
          }}</span>
          <div class="icon" @click="handleUseTools">
            <Icon type="md-add" color="#187BDB" />{{
              $t("maintenance.AddTools")
            }}
          </div>
          <div class="tableContent pd16" style="width: 100%">
            <Table class="resizable-table" border @on-column-width-resize="(a, b, c, d) => {
              onColumnWidthResize(a, b, c, d, 'AddToolsmodaltable');
            }
              " ellipsis ref="selection" :columns="columns" :data="toolsData">
              <template slot-scope="{ row, index }" slot="toolNum">
                <div v-if="!row.isEdit">
                  <Row>
                    <Col :span="20">
                    <span>{{ row.qty }}</span>
                    </Col>
                    <Col :span="4">
                    <Icon type="ios-brush-outline" size="18" color="#180fff" @click="handleToolsEdit(row, index)"></Icon>
                    </Col>
                  </Row>
                </div>
                <div v-else>
                  <Row>
                    <Col :span="20">
                    <InputNumber :min="1" v-model="row.qty" />
                    </Col>
                    <Col :span="4">
                    <Icon type="ios-checkmark" size="35" color="#180fff" @click="handleUnToolsEdit(row, index)"
                      style="display: inline-block"></Icon>
                    </Col>
                  </Row>
                </div>
              </template>
              <template slot-scope="{ row ,index}" slot="action">
                <!--            <span class="operationBtn" @click="handleToolsEdit(row,index)">{{$t('common.Edit')}}</span>-->
                <span class="operationBtn" @click="handleToolsDelete(row,index)">{{
                  $t("common.Delete")
                }}</span>
              </template>
            </Table>
          </div>
        </div>

        <use-tools-modal ref="userToolsModal" @handleSelectUseTools="handleSelectUseTools" />
        <use-goods-modal ref="userGoodsModal" @handleUseGoodsOk="handleUseGoodsOk" />
      </div>
      <div slot="footer">
        <Button type="default" @click="visible = false">{{
          $t("common.Cancle")
        }}</Button>
        <Button type="primary" :loading="loadingVisible" @click="handleOk">{{
          $t("maintenance.Confirmed")
        }}</Button>
      </div>
    </Modal>
    <!-- 使用工具添加 -->
    <Modal :mask-closable="false" v-model="arrVisible" width="640" class="addModal modal-content-layout" :title="$t('maintenance.AddTools')">
      <div class="addProject">
        <Form label-position="top">
          <FormItem :label="$t('maintenance.Materialno')" required>
            <Select filterable clearable v-model="tablefrom.toolCode" :remote-method="toolcodeChange"
              @on-change="toolChange">
              <Option v-for="item in toolList" :value="item.deviceMId" :label="item.deviceMId" :key="item.id" />
            </Select>
          </FormItem>
          <FormItem :label="$t('maintenance.ToolName')" required>
            <Input class="inputWrapper" v-model="tablefrom.toolName" readonly />
          </FormItem>
          <FormItem :label="$t('spareParts.quantity')" required>
            <InputNumber :min="1" v-model="tablefrom.qty" />
          </FormItem>
          <FormItem :label="$t('保管方式')">
            <Input class="inputWrapper" v-model="tablefrom.toolMode" clearable />
          </FormItem>
        </Form>
      </div>

      <div slot="footer">
        <Button type="default" @click="close">{{ $t("common.Cancle") }}</Button>
        <Button type="primary" @click="addTableobj">{{
          $t("maintenance.Confirmed")
        }}</Button>
      </div>
    </Modal>

    <!-- 使用物料添加 -->
    <Modal :mask-closable="false" v-model="materialVisible" width="640" class="addModal modal-content-layout"
      :title="`${$t('maintenance.materialinfo')}`">
      <div class="addProject">
        <Form v-if="materialVisible" ref="materialForm" label-position="top">
          <FormItem :label="$t('maintenance.MaterialnoInfo')" required>
            <Select filterable clearable v-model="tableMaterial.materialCode" :remote-method="materielNoChangeAdd"
              @on-change="materieChange">
              <Option v-for="item in materielNoList" :value="item.materialCode" :label="item.materialName"
                :key="item.id" />
            </Select>
          </FormItem>
          <FormItem :label="$t('common.GoodsName')" required>
            <Input class="inputWrapper" readonly v-model="tableMaterial.materialName" />
          </FormItem>
          <FormItem :label="$t('common.Specification')">
            <Input class="inputWrapper" readonly v-model="tableMaterial.specification" />
          </FormItem>
          <FormItem :label="$t('spareParts.quantity')" required>
            <InputNumber :min="1" :disabled="tableMaterial.numStatus" v-model="tableMaterial.qty" />
          </FormItem>
        </Form>
      </div>
      <div slot="footer">
        <Button type="default" @click="materiaClose">{{
          $t("common.Cancle")
        }}</Button>
        <Button type="primary" @click="materiaTableobj">{{
          $t("maintenance.Confirmed")
        }}</Button>
      </div>
    </Modal>
    <Modal :mask-closable="false" v-model="delFaultCodeShowF" title="">
      <Row class="enableContent">
        <Col span="24" class="enableContentInner">
        <img width="95px" src="~images/event/del.png" alt="" />
        </Col>
        <Col span="24" class="enableTips">
        <span>{{
          messageStrA + "," + messageStrB + "未添加,是否确认保存?"
        }}</span>
        </Col>
      </Row>
      <div slot="footer">
        <Button type="default" @click="delFaultCodeShowF = false">{{
          $t("common.Cancle")
        }}</Button>
        <Button type="primary" @click="ConfirmeClick">{{
          $t("maintenance.Confirmed")
        }}</Button>
      </div>
    </Modal>

    <gallery :images="galleryImages" :index="galleryIndex" @close="galleryIndex = null" />
    <iframeModalCompent v-if="iframeShow" :isStudy="false" :iframeShow="iframeShow" :iframeModalSrc="iframeModalSrc"
      @closeIframe="iframeShow = false"></iframeModalCompent>
  </div>
</template>

<script>
import { fileUpload } from "@/api/maintenance";
import iframeModalCompent from "@/views/knowledgeBase/modal/iframe.vue";
import VueGallery from "vue-gallery";
import UseGoodsModal from "./useGoodsModal";
import UseToolsModal from "./useToolsModal";

import toggleTableOperation from "@/mixins/toggleTableOperation";
export default {
  name: "addModal",
  mixins: [toggleTableOperation],
  components: {
    UseGoodsModal,
    UseToolsModal,
    gallery: VueGallery,
    iframeModalCompent,
  },
  props: [],
  data() {
    return {
      galleryIndex: null,
      galleryImages: [],
      messageStrA: "",
      messageStrB: "",
      triggerCycleInfo: "",
      toolList: [],
      deviceMIdList: [],
      delFaultCodeShowF: false,
      materielNoList: [],
      tableMaterial: {
        qty: 1,
      },
      tablefrom: {},
      materialVisible: false,
      arrVisible: false,
      id: "",
      formInline: {
        triggerCycle: [],
        maxValue: null,
        minValue: null,
        itemHours: null,
      },
      visible: false,
      loadingVisible: false,
      deviceList: [
        { label: "A", value: "A" },
        { label: "B", value: "B" },
        { label: "C", value: "C" },
      ],
      // positionList: [],
      deviceNameList: [],
      classifyList: [],
      levels: [
        { value: "1", label: "一级保养" },
        { value: "2", label: "二级保养" },
        { value: "3", label: "三级保养" },
      ],
      weeks: [
        { name: "班次", label: "7" },
        { name: "日", label: "1" },
        { name: "周", label: "2" },
        { name: "月", label: "3" },
        { name: "季度", label: "4" },
        { name: "半年", label: "5" },
        { name: "一年", label: "6" },
        { name: "计时", label: "8" },
      ],
      materColumns: [
        {
          type: "index",
          width: 90,
          title: `${this.$t("common.index")}`,
          align: "center",
        },
        {
          title: `${this.$t("maintenance.MaterialnoInfo")}`,
          key: "code",
          align: "center",
          resizable: true,
          tooltip: true,
          width: 180,
        },
        // {
        //   title: `${ this.$t('maintenance.materialcode') }`,
        //   key: 'materialCode',
        //   align: 'center'
        // },
        {
          title: `${this.$t("common.GoodsName")}`,
          key: "materialName",
          align: "center",
          resizable: true,
          tooltip: true,
          width: 180,
        },
        {
          title: `${this.$t("spareParts.Specification")}`,
          key: "specification",
          align: "center",
          resizable: true,
          tooltip: true,
          width: 180,
        },
        {
          title: `${this.$t("spareParts.quantity")}`,
          key: "num",
          slot: "num",
          width: 180,
          align: "center",
          resizable: true,
        },
        // {
        //   title: `${this.$t('maintenance.unitprice')}`,
        //   key: 'unitPrice',
        //   align: 'center'
        // },
        {
          title: `${this.$t("common.operation")}`,
          key: "action",
          align: "center",
          slot: "action",
          width: 180,
        },
      ],
      columns: [
        {
          type: "index",
          width: 90,
          title: `${this.$t("common.index")}`,
          align: "center",
        },
        {
          title: `${this.$t("maintenance.ToolMaterialNo")}`,
          key: "toolCode",
          align: "center",
          resizable: true,
          tooltip: true,
          width: 180,
        },
        {
          title: `${this.$t("maintenance.Toolnames")}`,
          key: "toolName",
          align: "center",
          resizable: true,
          tooltip: true,
          width: 180,
        },
        // {
        //   title: `${ this.$t('equipCheck.Model') }`,
        //   key: 'toolModel'
        // },
        // {
        //   title: '品牌',
        //   key: 'toolBrand'
        // },
        {
          title: `${this.$t("spareParts.quantity")}`,
          key: "qty",
          slot: "toolNum",
          align: "center",
          resizable: true,
          tooltip: true,
          width: 180,
        },
        {
          title: `${this.$t("保管方式")}`,
          key: "toolMode",
          align: "center",
          resizable: true,
          tooltip: true,
          width: 180,
        },
        {
          title: `${this.$t("common.operation")}`,
          key: "action",
          align: "center",
          slot: "action",
          width: 180,
        },
      ],
      wlColumns: [
        {
          title: `${this.$t("maintenance.materialcode")}`,
          key: "maCode",
          resizable: true,
        },
        {
          title: `${this.$t("maintenance.materialname")}`,
          key: "maName",
          resizable: true,
        },
        {
          title: `${this.$t("spareParts.quantity")}`,
          key: "num",
          slot: "num",
          resizable: true,
        },
        {
          title: `${this.$t("maintenance.Unitprice")}`,
          key: "maPrice",
          resizable: true,
        },
        {
          title: `${this.$t("maintenance.totalprice")}`,
          key: "totalPrice",
          resizable: true,
        },
        {
          title: `${this.$t("common.operation")}`,
          key: "action",
          slot: "action",
          resizable: true,
          tooltip: true,
          width: 100,
        },
      ],
      materData: [],
      toolsData: [],
      deviceTypeList: [],
      wlData: [],
      tarGetattachment: [],
      deviceMId: "",
      iframeShow: false, // 预览弹窗
      iframeModalSrc: "",
    };
  },
  created() {
    this.getColumnWidth(this.materColumns, "Addmaterialmodaltable");
    this.getColumnWidth(this.columns, "AddToolsmodaltable");
    // this.handleRemote();
    // this.getFaultCategory("设备类型");
    // this.getDeviceList();
    // this.getPositionList()
    // this.getClassifyList()
  },
  methods: {
    debounceSerach(fn, delay) {
      let _this = this;
      return function f(...args) {
        if (_this.timeID) {
          clearTimeout(_this.timeID);
        }
        _this.timeID = setTimeout(() => {
          fn(args);
        }, delay);
      };
    },
    deviceMIdChange(val) {
      if (val) {
        const obj = this.deviceMIdList.find((item) => item.moldCode === val);
        if (obj.moldGrade) {
          this.formInline.moldGrade = obj.moldGrade;
        }
        if (obj.mmoldCode) {
          this.formInline.mmoldCode = obj.mmoldCode;
        }
        if (obj.moldName) {
          this.formInline.mmoldName = obj.moldName;
        }
      }
    },
    handleRemote(query, source) {
      if (!query) {
        return;
      }
      // console.log(query,source)

      // const fn = this.debounceSerach(()=>{
      // let _query = query.split('-')

      // if (Array.isArray(_query)) _query = _query[0]
      // const deviceMId = _query
      // this.deviceMId = _query
      this.axios({
        method: "post",
        url: "/dms/moldinfo/getDeviceTzList",
        data: {
          pageNum: 1,
          pageSize: 999999,
          moldCode: query,
        },
      }).then((res) => {
        if (res.code === 200) {
          this.deviceMIdList = res.data.records;
        } else {
          this.$Message.warning({
            content: res.msg,
            duration: 6,
            closable: true,
          });
        }
      });
      // },300)
      // fn()
    },
    queryChange(val) {
      if (val) {
        this.formInline.deviceType = val;
      }
    },
    createType(val) {
      this.deviceTypeList.push({
        label: val,
        value: val,
      });
    },
    deleteAttachment(item) {
      this.tarGetattachment = this.tarGetattachment.filter(
        (val) => val.filePath !== item.filePath
      );
    },

    previewClicjk(item, index, arr) {
      if (this.util.fileType(item.fileName) === "file") {
        this.iframeShow = true;
        let env = process.env.NODE_ENV;
        let origin = window.location.origin;
        console.log(origin);
        let path = "/";
        if (env === "tong") {
          path = "";
        }
        let fileUrl = origin + this.util.filePathToUrl(item.filePath);
        this.iframeModalSrc =
          origin + path + `/fileServer/onlinePreview?url=${fileUrl}`;
      } else {
        if (this.galleryIndex) {
          this.galleryIndex = null;
        }
        let list = [];
        list = arr.filter((val) => this.util.fileType(val.fileName) !== "file");
        this.galleryImages = list.map((val) => {
          let objPath = val.filepath || val.filePath;
          if (this.util.fileType(objPath) === "video") {
            val.filetype = "video/mp4";
          }
          if (this.util.fileType(objPath) === "image") {
            val.filetype = "image/jpeg";
          }
          return {
            type: val.filetype,
            href: val.fileUrl,
          };
        });
        this.galleryIndex = this.galleryImages.findIndex(
          (val) =>
            val.href === this.util.filePathToUrl(item.filepath || item.filePath)
        );
      }
    },
    dataURLtoFileFun(dataurl, filename) {
      let arr = dataurl.split(",");
      let mime = arr[0].match(/:(.*?);/)[1];
      let bstr = atob(arr[1]);
      let n = bstr.length;
      let u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new File([u8arr], filename, { type: mime });
    },
    afterRead(file) {
      // console.log(file)
      // if(file.file.type.indexOf('video') !== -1 || file.file.type.indexOf('image') !== -1){
      let formData = new FormData();
      formData.append("dir", "device");
      // console.log(this.dataURLtoFileFun(file.content, "file.jpg"))
      // console.log(file)
      formData.append("file", file.file);
      // if (file.file.name.indexOf('jpg') !== -1){
      //   formData.append("file", this.dataURLtoFileFun(file.content, "file.jpg"));
      // }
      // if (file.file.name.indexOf('png') !== -1){
      //   formData.append("file", this.dataURLtoFileFun(file.content, "file.png"));
      // }
      // if (file.file.name.indexOf('mp4') !== -1){
      //   formData.append("file", this.dataURLtoFileFun(file.content, "file.video"));
      // }
      let config = {
        headers: {
          "Content-Type": "multipart/form-data",
        },
      };
      // console.log(formData)
      fileUpload(formData, config).then((res) => {
        if (res.code == 200) {
          if (!res.data.fileLength) {
            return;
          }
          const data = [res.data].map((val) => ({
            itemId: this.id,
            fileName: val.fileName,
            filePath: val.filepath,
            fileUrl: val.fileUrl,
            previewPath: val.previewPath,
          }));
          console.log(data);
          console.log(this.tarGetattachment);
          this.tarGetattachment.push(data[0]);

          // this.axios({
          //   method: 'post',
          //   url: '/dms/dcmAttachment/itemUpload',
          //   data
          // }).then(res=>{
          //   if (res.code == 200){
          //     this.$Message.success(res.msg)
          //   }else {
          //     this.$Message.error(res.msg)
          //   }
          // })
        }
      });
      // }else{
      //   this.$Message.error('只能上传视频/图片')
      // }
    },
    handleUnToolsEdit(row) {
      this.$set(row, "isEdit", false);
      this.toolsData.forEach((item) => {
        if (item.toolCode == row.toolCode) {
          item.qty = row.qty;
        }
      });
    },
    handleMaterEdit(row) {
      this.$set(row, "isEdit", false);
      this.materData.forEach((item) => {
        if (item.id == row.id) {
          item.qty = row.qty;
        }
      });
    },
    handleToolsEdit(row) {
      this.$set(row, "isEdit", true);
    },
    //获取故障数据
    getFaultCategory(name) {
      this.axios({
        method: "get",
        url: "/dms/faultCategory/basicDict",
        params: { name },
      }).then((res) => {
        if (res.code === 200) {
          if (name === "故障分类") {
            this.faultCategoryList = res.data.map((item) => {
              if (item.value) return item;
            });
          } else if (name === "设备类型") {
            this.deviceTypeList = res.data.map((item) => {
              if (item.value) return item;
            });
          }
        } else {
          this.$Message.warning({
            content: res.msg,
            duration: 6,
            closable: true,
          });
        }
      });
    },
    deviceNameChange(val) {
      this.$set(this.formInline, "bomId", "");
      this.materielNoList = [];

      if (val) {
        this.formInline.deviceType = val;
        this.materielNoChange("");
      }
    },
    materieChange(val) {
      if (!val) {
        this.tableMaterial = {
          code: '',
          materialName: '',
          specification: '',
          qty: this.tableMaterial.qty,
        }
        return;
      }
      const obj = this.materielNoList.find((item) => item.materialCode == val);
      if (obj) {
        this.tableMaterial = {
          isEdit: false,
          // seqNo: obj.id,
          code: obj.materialCode,
          materialName: obj.materialName,
          specification: obj.materialModel,
          // unitPrice:obj.purchasePrice,
          qty: 1,
        };
        if (obj.manageType == 1) {
          this.tableMaterial.qty = 1;
          this.tableMaterial.numStatus = true;
        }
      }
    },
    toolNum(val) {
      this.tablefrom.qty = val;
    },
    toolChange(val) {
      if (!val) {
        return;
      }
      const obj = this.toolList.find((item) => item.deviceMId == val);
      if (obj) {
        this.tablefrom = {
          isEdit: false,
          toolCode: obj.deviceMId,
          toolName: obj.deviceName,
          qty: 1,
        };
      }
    },
    toolcodeChange(val) {
      if (!val) {
        return;
      }
      const fn = this.debounceSerach(() => {
        const params = {
          deviceMId: val,
          deviceType: "工具",
          pageNum: 1,
          pageSize: 9999,
        };
        this.axios({
          method: "post",
          url: "/dms/device/page",
          data: params,
        }).then((res) => {
          if (res.code === 200) {
            if (res.data) {
              this.toolList = res.data.records;
            }
          } else {
            this.$Message.warning({
              content: res.msg,
              duration: 6,
              closable: true,
            });
          }
        });
      }, 360);
      fn();
    },
    materielNoChangeBom(val) {
      console.log(val);
    },
    materielNoChange(val, value) {
      // if (!val){
      //    return
      // }

      if (
        val &&
        this.materielNoList.find(
          (item) => item.materielNo + "-" + item.materielName === val
        )
      ) {
        return;
      }

      const fn = this.debounceSerach(() => {
        const params = {
          deviceType: this.formInline.deviceType,
          param: val,
        };
        this.axios({
          method: "post",
          // url: '/dms/applyUse/querySearch',
          url: "/dms/dmsBom/queryByDeviceTypeAndDeviceName",
          // url: '/dms/dmsBom/queryMateriel',
          data: { ...params },
        }).then((res) => {
          if (res.code === 200) {
            if (res.data) {
              this.materielNoList = res.data;
            }
            if (value) {
              this.formInline.bomId = Number(value);
            }
          } else {
            this.$Message.warning({
              content: res.msg,
              duration: 6,
              closable: true,
            });
          }
        });
      }, 360);
      fn();
    },
    materielNoChangeAdd(val, value) {
      // if (!val){
      //    return
      // }

      if (
        val &&
        this.materielNoList.find(
          (item) => item.materielNo + "-" + item.materielName === val
        )
      ) {
        return;
      }

      const fn = this.debounceSerach(() => {
        const params = {
          materialCode: val,
          pageNum: 1,
          pageSize: 9999,
        };
        this.axios({
          method: "post",
          url: "/dms/material/page",
          data: { ...params },
        }).then((res) => {
          if (res.code === 200) {
            if (res.data) {
              this.materielNoList = res.data.records;
            }
            if (value) {
              this.formInline.bomId = Number(value);
            }
          } else {
            this.$Message.warning({
              content: res.msg,
              duration: 6,
              closable: true,
            });
          }
        });
      }, 360);
      fn();
    },
    materiaClose() {
      this.materialVisible = false;
    },
    close() {
      this.arrVisible = false;
    },
    materiaTableobj() {
      // if (!this.tableMaterial.materielNo) {
      //   this.$Message.error(({ content: '请填写工具物料号!', duration: 3, closable: true }));
      //   return;
      // }
      if (!this.tableMaterial.code) {
        this.$Message.error({
          content: "请填写物料号!",
          duration: 3,
          closable: true,
        });
        return;
      }
      if (!this.tableMaterial.materialName) {
        this.$Message.error({
          content: "请填写品名!",
          duration: 3,
          closable: true,
        });
        return;
      }
      // if (!this.tableMaterial.specification) {
      //   this.$Message.error({
      //     content: "请填写规格!",
      //     duration: 3,
      //     closable: true,
      //   });
      //   return;
      // }
      if (!this.tableMaterial.qty) {
        this.$Message.error({
          content: "请填写数量!",
          duration: 3,
          closable: true,
        });
        return;
      }
      const flag = this.materData.find(
        (val) => val.code === this.tableMaterial.code
      );
      if (flag) {
        this.$Message.error({
          content: "该物料已添加",
          duration: 3,
          closable: true,
        });
        return;
      }
      this.materData.push(this.tableMaterial);
      this.materiaClose();
    },
    addTableobj() {
      if (!this.tablefrom.toolCode) {
        this.$Message.error({
          content: "请填写工具物料号!",
          duration: 3,
          closable: true,
        });
        return;
      }
      if (!this.tablefrom.toolName) {
        this.$Message.error({
          content: "请填写工具名称!",
          duration: 3,
          closable: true,
        });
        return;
      }
      if (!this.tablefrom.qty) {
        this.$Message.error({
          content: "请填写数量!",
          duration: 3,
          closable: true,
        });
        return;
      }
      const flag = this.toolsData.some(
        (val) => val.toolName === this.tablefrom.toolName
      );
      if (flag) {
        this.$Message.error({
          content: "该工具已添加",
          duration: 3,
          closable: true,
        });
        return;
      }
      this.toolsData.push(this.tablefrom);
      this.arrVisible = false;
    },
    /**************基础数据**********************/
    categorySelectChange(categoryName) {
      if (categoryName) {
        this.axios({
          method: "get",
          url: "/dms/dcmMaintainItem/queryDeviceNames",
          params: {
            categoryName,
          },
        }).then((res) => {
          if (res.code == 200) {
            this.deviceNameList = res.data.map((val) => ({
              label: val,
              value: val,
            }));
          }
        });
      }
    },
    getClassifyList() {
      this.axios({
        method: "get",
        url: "/dms/dcmMaintainClassify/getSelectList",
        params: {},
      }).then((res) => {
        if (res.code === 200) {
          this.classifyList = res.data;
        } else {
          this.$Message.warning({
            content: res.msg,
            duration: 6,
            closable: true,
          });
        }
      });
    },
    show(rowData) {
      let row = JSON.parse(JSON.stringify(rowData));
      this.deviceMIdList = [];
      this.id = row.id;
      this.formInline={};
      if (!this.id) {
        this.formInline = {
          // unitTime: null,
          // minValue: null,
          // itemHours: null,
          // sequence: '',
          unitTime: 0,
        };
        this.materData = [];
        this.toolsData = [];
        this.wlData = [];
        this.visible = true;
        this.tarGetattachment = [];
      } else {
        // this.handleRemote(row.mmoldCode);
        // this.formInline = {
        //   // ...row,
        //   mmoldCode: row.mmoldCode,
        // };
        this.$nextTick(()=>{
          this.$set(this,'formInline',{...row});
        })
        this.formInline.servicingSop = row.servicingSop;
        this.tarGetattachment = this.formInline.servicingSop || [];
        this.materData = row.materialList;
        this.toolsData = row.toolList;
        this.visible = true;
        // this.getDetail(this.id)
      } 
    },
    getDetail(id) {
      this.tarGetattachment = [];
      this.axios({
        method: "get",
        url: "/dms/dcmMaintainItem/queryById",
        params: {
          id,
        },
      }).then((res) => {
        if (res.code === 200) {
          this.formInline.deviceMId = res.data.deviceMId;
          this.$nextTick(() => {
            this.formInline = {
              ...res.data,
              bomId: "",
              triggerCycle: res.data.triggerCycle
                ? res.data.triggerCycle.split(",")
                : [],
              minValue: res.data.minValue ? Number(res.data.minValue) : "",
              maxValue: res.data.maxValue ? Number(res.data.maxValue) : "",
            };
            if (res.data.attachment && res.data.attachment.length) {
              this.tarGetattachment = res.data.attachment || [];
            }
            if (res.data.deviceMId) {
              let deviceMId = res.data.deviceMId || "";
              this.handleRemote(deviceMId, 1);
            }
            if (res.data.deviceType) {
              let bomOrg = res.data.bomOrg || "";
              this.materielNoChange(bomOrg.split("-")[0], res.data.bomId);
            }
            if (this.formInline.categoryName) {
              this.categorySelectChange(this.formInline.categoryName);
            }
            // this.wlData = res.data.dcmMaintainMaterialList.map(item => {
            //   return {
            //     ...item,
            //     maCode: item.materialCode,
            //     maName: item.materialName,
            //     maPrice: item.unitPrice,
            //     isEdit: false,
            //   }
            // })
            this.toolsData = res.data.dcmMaintainToolList.map((item) => {
              return {
                ...item,
                isEdit: false,
              };
            });
            this.materData = res.data.dcmMaintainMaterialList.map((item) => {
              return {
                ...item,
                isEdit: false,
              };
            });
          });
        } else {
          this.$Message.warning({
            content: res.msg,
            duration: 6,
            closable: true,
          });
        }
      });
    },
    handleToolsChange(row) {
      this.$set(row, "isEdit", true);
      // this.toolsData[index].toolNum = event.target.value
    },
    levelCheck(e) {
      e.target.value = e.target.value.replace(/(^\s*)|(\s*$)/g, "");
      const reg = /[^\d.]/g;
      e.target.value = e.target.value.replace(reg, "");
      e.target.value = e.target.value.replace(/^\./g, "");
      e.target.value = e.target.value
        .replace(".", "$#$")
        .replace(/\./g, "")
        .replace("$#$", ".");
      e.target.value = e.target.value.replace(
        /^(\-)*(\d+)\.(\d\d).*$/,
        "$1$2.$3"
      );
    },
    handleGoodsChange(event, index, row) {
      console.log(row);
      console.log(event.target.value, index);
      this.wlData[index].num = event.target.value;
      this.wlData[index].totalPrice = parseFloat(
        Number(row.maPrice) * Number(event.target.value)
      ).toFixed(2);
    },
    handleGoodsEdit(row, index) {
      this.wlData[index].isEdit = true;
    },
    handleUnGoodsEdit(row, index) {
      this.wlData[index].isEdit = false;
    },
    handleGoodsDelete(row) {
      this.wlData = this.wlData.filter((item) => item.id != row.id);
    },
    handleToolsDelete(row) {
      this.toolsData = this.toolsData.filter((item) => item.toolCode != row.toolCode);
    },
    handlemDelete(row) {
      this.materData = this.materData.filter((item) => item.id != row.id);
    },
    handleUseTools() {
      this.arrVisible = true;
      this.tablefrom = {
        qty: 1,
      };
      // this.$refs.userToolsModal.show()
    },
    handleMaterial() {
      this.tableMaterial = {
        qty: 1,
        materialName:'',
        specification:'',
        code:'',
      };
      this.materielNoList = [];
      this.materialVisible = true;
      this.$refs.materialForm.resetFields();
    },
    handleSelectUseTools(data) {
      this.toolsData = [...this.toolsData, ...data];
      // if (this.toolsData.length) {
      //   let arr = this.toolsData.filter(item => data.some(x => x.id == item.id))
      //   console.log(arr)
      //   if (arr.length) {
      //     this.$Message.warning(({content: '有重复数据，请重新选择！', duration: 6, closable: true}));
      //     return false
      //   }
      //   this.toolsData = [...this.toolsData, ...data]
      // }else {
      //   this.toolsData = [...this.toolsData, ...data]
      // }
    },
    handleUseGoods() {
      this.$refs.userGoodsModal.show();
    },
    handleUseGoodsOk(data) {
      console.log(data);
      // this.wlData.push(data)
      this.wlData = [...this.wlData, ...data];
    },
    ConfirmeClick() {
      let data = {
        ...this.formInline,
        // triggerCycle: this.triggerCycleInfo,
        materialList: this.materData,
        toolList: this.toolsData,
        servicingSop: this.tarGetattachment || [],
      };
      if (!this.id) {
        this.loadingVisible = true;
        this.axios({
          method: "post",
          url: "/dms/servicingItem/add",
          data,
        })
          .then((res) => {
            if (res.code === 200) {
              this.visible = false;
              this.$emit("handleSearch");
              this.$Message.success({
                content: "新增成功！",
                duration: 2,
                closable: true,
              });
            } else {
              this.$Message.warning({
                content: res.msg,
                duration: 6,
                closable: true,
              });
            }
          })
          .finally(() => {
            this.loadingVisible = false;
          });
      } else {
        this.loadingVisible = true;
        this.axios({
          method: "post",
          url: "/dms/servicingItem/update",
          data,
        })
          .then((res) => {
            if (res.code === 200) {
              this.visible = false;
              this.$emit("handleSearch");
              this.$Message.success({
                content: "编辑成功！",
                duration: 2,
                closable: true,
              });
            } else {
              this.$Message.warning({
                content: res.msg,
                duration: 6,
                closable: true,
              });
            }
          })
          .finally(() => {
            this.loadingVisible = false;
          });
      }
      this.delFaultCodeShowF = false;
    },
    handleOk() {
      console.log(this.formInline);
      if (
        this.formInline.unitTime === "" ||
        !this.formInline.itemBase ||
        !this.formInline.itemProject ||
        !this.formInline.itemMethod ||
        // !this.formInline.mmoldCode ||
        // !this.formInline.moldGrade ||
        // !this.formInline.mmoldName ||
        this.formInline.itemLevel === "" ||
        this.formInline.itemLevel === undefined
      ) {
        this.$Message.warning({
          content: "请将信息填写完整！",
          duration: 6,
          closable: true,
        });
        return false;
      }
      // if (this.formInline.minValue > this.formInline.maxValue) {
      //   this.$Message.warning(({content:'下限不能大于上限！',duration:6,closable:true}))
      //   return false
      // }
      // let dcmMaintainMaterialList = []
      // let dcmMaintainToolList = []
      // dcmMaintainMaterialList = this.wlData.map(item => {
      //   return {
      //     materialCode: item.maCode,
      //     materialName: item.maName,
      //     num: item.num,
      //     totalPrice: item.totalPrice,
      //     unitPrice: item.maPrice
      //   }
      // })
      // dcmMaintainToolList = this.toolsData.map(item => {
      //   return {
      //     toolId: item.toolId ? item.toolId : item.id ,
      //     toolNum: item.toolNum
      //   }
      // })
      let flag = false;
      if (!(this.materData && this.materData.length)) {
        flag = true;
        this.messageStrA = "使用物料";
      }
      if (!(this.toolsData && this.toolsData.length)) {
        flag = true;
        this.messageStrB = "使用工具";
      }
      if (flag) {
        this.delFaultCodeShowF = true;
      } else {
        this.ConfirmeClick();
      }
    },
  },
};
</script>
<style scoped lang="scss">
::v-deep .ivu-input-number {
  width: 100% !important;
}
</style>
<style lang="scss">
.addProject {
  .titleItem {
    position: relative;
    font-size: 18px;
    font-weight: bold;
    padding: 10px;

    .checkObject {
      display: flex;
      flex-wrap: wrap;
      padding: 20px 0;
      font-family: "Arial Normal", "Arial", sans-serif;
      font-weight: 400;
      font-style: normal;
      letter-spacing: normal;

      .checkObjectItem {
        display: flex;
        flex: 1;
        flex-wrap: wrap;
        align-items: center;

        .fujianList {
          width: 100%;
          // overflow: hidden;
          height: 90px;
          // white-space:nowrap;
          // overflow-x: scroll;

          //overflow-y: auto;
          //display: -webkit-box;
          &::-webkit-scrollbar {
            width: 0px;
            height: 0;
          }

          .item {
            cursor: pointer;
            float: left;
            // padding-left: 10px;
            width: 134px;
            height: 80px;
            position: relative;

            .fileSty {
              display: flex;
              justify-content: center;
              align-items: center;
              background: rgb(255, 237, 137);
              width: 100%;
              height: 100%;
            }
            video {
              width: 100%;
              height: 100%;
              object-fit: fill;
            }

            img {
              width: 100%;
              height: 100%;
            }
          }
        }

        .van-uploader {
          width: 100%;

          .van-uploader__wrapper {
            width: 100%;

            .van-uploader__upload {
              width: 100%;
              margin: 0 !important;
            }
          }
        }

        .checkObjectNameNone {
          border: none !important;
          background: #fff !important;
          width: 20% !important;
        }

        .checkObjectName {
          height: 40px;
          line-height: 40px;
          width: 100%;
          font-size: 13px;
          border: 1px solid #eeeeee;
          background: #f5f6f7;
          text-align: left;
          padding: 0 10px;
          color: #666666;
        }

        .required::before {
          content: "*";
          color: red;
        }

        .checkObjectValueNone {
          width: 70%;
        }

        .checkObjectValue {
          height: 40px;
          line-height: 40px;
          width: 100%;
          font-size: 13px;
          border: 1px solid #eeeeee;
          padding-left: 10px;
          color: #333;
          display: flex;
          align-items: center;

          .select {
            .ivu-select-selection {
              border: none;
              box-shadow: none;
              font-size: 13px;
            }
          }

          .inputWrapper {
            .ivu-input {
              border: none;
              box-shadow: none;
            }
          }

          .inputNumberWrapper {
            width: 100%;
            border: 0;
            box-shadow: none;
          }
        }
      }
    }

    .searchBox {
      .label {
        display: flex;
      }
    }

    .contentTable {
      padding: 20px;
    }
  }

  .titleItemNone::before {
    content: none !important;
  }

  .titleItem::before {
    display: none;
    //content: "";
    //position: absolute;
    //width: 3px;
    //height: 20px;
    //top: 13px;
    //left: 0px;
    //background: #187bdb;
  }

  .tab {
    display: flex;
    align-items: center;
    flex-wrap: wrap;

    .icon {
      border: 1px solid #187bdb;
      border-radius: 30px;
      padding: 5px 20px 5px 20px;
      display: flex;
      align-items: center;
      //margin-left/*:*/ 20px;
      color: #187bdb;
      margin: 16px;
      cursor: pointer;

      i {
        font-size: 20px;
        font-weight: bold;
      }
    }
  }
}
.demo-upload-list {
  position: relative;
  width: 60px;
  height: 60px;
  text-align: center;
  line-height: 60px;
  border-radius: 4px;
  background: #fff;
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.2);
  margin-left: 15px;

  img {
    width: 100%;
    height: 100%;
  }

  .delIcon {
    position: absolute;
    right: -10px;
    top: -10px;
    color: red;
    font-size: 20px;
    background: #fff;
    border-radius: 50%;
    cursor: pointer;
  }
}
</style>
